package com.tuling.controller;

import com.tuling.domain.User;
import com.tuling.service.UserService;
import com.tuling.service.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "RegisterServlet", value = "/RegisterServlet")
public class RegisterServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取参数
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String pwd1 = request.getParameter("pwd1");
        String pwd2 = request.getParameter("pwd2");
        // 封装User实例
        User user = new User(email, phone, pwd1, email);
        // 调用业务逻辑层处理逻辑
        User addUser = userService.add(user);
        // 根据结果响应前端
        if (addUser!=null) {
            HttpSession session = request.getSession();
            session.setAttribute("user", addUser);
            // 重定向到首页
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        } else {
            request.getRequestDispatcher("/reg.jsp").forward(request,response);
        }

    }
}
